﻿var shop = new Shop();
function Shop() {
    var currentItemIndex = 0;
    var keys = [];
    var item = {};

    var showCartDetailsUrl;
    var cartTotalUrl;
    var createOrderUrl;
    var showOrderDetailsUrl;
    var showClientDetailsUrl;
    var loadingUrl;
    var cartUrl;
    var addToOrderByAdminUrl;
    this.init = function (properties) {
        showCartDetailsUrl = properties["showCartDetailsUrl"];
        cartTotalUrl = properties["cartTotalUrl"];
        showOrderDetailsUrl = properties["showOrderDetailsUrl"];
        createOrderUrl = properties["createOrderUrl"];
        showClientDetailsUrl = properties["showClientDetailsUrl"];
        loadingUrl = properties["loadingUrl"];
        cartUrl = properties["cartUrl"];
        addToOrderByAdminUrl = properties["addToOrderByAdminUrl"];
        updateCart();
    }
    this.showCartDetails = function () {
        if ($("#content").find("#cart-details").length != 0) {
            var items = getProductsInsideCart();
            $.ajax({
                url: showCartDetailsUrl,
                type: "POST",
                data: JSON.stringify(items),
                dataType: "html",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $("#cart-details").html(data);
                    updateTotal();
                }

            });

        }
    }
    this.showOrderDetails = function () {
        if ($("#content").find("#order-details").length != 0) {
            var items = getProductsInsideCart();
            $.ajax({
                url: showOrderDetailsUrl,
                type: "POST",
                data: JSON.stringify(items),
                dataType: "html",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $("#order-details").html(data);
                    updateTotal();
                }
            });
        }
    }
    this.showClientDetails = function () {
        if ($("#content").find("#client-details").length != 0) {
            var client = getClient();
            $.ajax({
                url: showClientDetailsUrl,
                type: "POST",
                data: JSON.stringify(client),
                dataType: "html",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $("#client-details").html(data);
                }
            });

        }
    }
    this.autoCompliteClientForm = function () {
        if ($("#content").find("#create-client-button").length != 0) {
            var client = $.parseJSON(localStorage.getItem("client"));
            var form = $("#create-client-button").closest("form");
            form.find("input[type='hidden'][name='Id']").val(client.Id);
            form.find("input[name='Title']").val(client.Title);
            form.find("input[name='Organization']").val(client.Organization);
            form.find("input[name='Email']").val(client.Email);
            form.find("input[name='Phone']").val(client.Phone);
            form.find("input[name='Adress']").val(client.Adress);
        }
    }
    function getClient() {
        return $.parseJSON(localStorage.getItem('client'));
    }
    /*function for events*/
    $("#choose-delivery-button").live("click",function(){
        var delivery = $("input[name='deliveryId']:checked").val();
        localStorage.setItem('deliveryId', delivery);
    })
    $("#create-client-button").live("click", function () {
        var form = $(this).closest("form");
        var client = {};
        client.Id = form.find("input[type='hidden'][name='Id']").val();
        client.Title = form.find("input[name='Title']").val();
        client.Organization = form.find("input[name='Organization']").val();
        client.Email = form.find("input[name='Email']").val();
        client.Phone = form.find("input[name='Phone']").val();
        client.Adress = form.find("input[name='Adress']").val();
        localStorage.setItem('client', JSON.stringify(client));
    });
    $("#create-order-button").live("click", function () {
        var items = getProductsInsideCart();
        var client = $.parseJSON(localStorage.getItem('client'));
        var deliveryId = localStorage.getItem('deliveryId');

        $.ajax({
            url: createOrderUrl,
            type: "POST",
            data: JSON.stringify({ items: items, client: client, deliveryId: deliveryId }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            beforeSend: function () {
                $("#content").html('<div style="text-align:center"><img src=\'' + loadingUrl + '\'/></div>');
            },
            success: function (data) {
                if (data.chek) {
                    showMsg(data.message.toString());
                    $("#content").html('<div style="text-align:center"><strong>Спасибо за Вашу покупку!</strong></div>');
                }
                else {
                    $("#dialog").html(data.message);
                    $("#dialog").dialog({
                        modal: true,
                        resizable: false,
                        buttons: {
                            Ok: function () {
                                window.location.replace(cartUrl);
                            }
                        }
                    });
                }
            }
        });
        return false;
    });
    $("#add-to-order-by-admin-button").live("click", function () {
        var items = getProductsInsideCart();
        var form = $(this).closest("form");
        var number = form.find("input[name='numerOfOrder']").val(); 
        $.ajax({
            url: addToOrderByAdminUrl,
            type: "POST",
            data: JSON.stringify({ items: items,number: number }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            beforeSend: function () {
                $("#content").html('<div style="text-align:center"><img src=\'' + loadingUrl + '\'/></div>');
            },
            success: function (data) {
                if (data.chek) {
                    showMsg(data.message.toString());
                    $("#content").html('<div style="text-align:center"><strong>Успешно добавлено!</strong></div>');
                }
                else {
                    $("#dialog").html(data.message);
                    $("#dialog").dialog({
                        modal: true,
                        resizable: false,
                        buttons: {
                            Ok: function () {
                                window.location.replace(cartUrl);
                            }
                        }
                    });
                }
            }
        });
        return false;
    });
    $(".cart-item-delete").live("click", function () {
        var form = $(this).closest("form");
        var item = parseForm($(form));
        deleteItemCart(item);
        updateCart();
        return false;
    });
    $(".cart-item-dec").live("click", function () {
        var form = $(this).closest("form");
        var item = parseForm($(form));
        var quantity = decrementItemCartQuantity(item);
        $(form).children(".cart-item-quantity").html(quantity);
        updateSumma(form, quantity);
        updateTotal();
        return false;
    });
    $(".cart-item-inc").live("click", function () {
        var form = $(this).closest("form");
        var item = parseForm($(form));
        var quantity = parseInt(incrimentItemCartQuantity(item));
        $(form).children(".cart-item-quantity").html(quantity);
        updateSumma(form, quantity);
        updateTotal();
        return false;
    });
    $("#clear-cart").live("click", function () {
        keys = getKeysFromStore();
        $.each(keys, function () {
            localStorage.removeItem(this);
        });
        localStorage.removeItem('keys');
        updateCart();

        return false;
    });
    $("#add-to-cart-button").live("click", function () {
        var forms = $(".shop-form");
        $.each(forms, function () {
            addItemToCart($(this));
        })
        updateCart();
        showMsg('Товар добавлен к корзину.');
        return false;
    });
    function showMsg(msg) {
        $("#dialog").html(msg);
        $("#dialog").dialog({
            modal: true,
            resizable: false,
            buttons: {
                Ok: function () {
                    $(this).dialog("close");
                }
            }
        });
    }
    function updateSumma(form, quantity) {
        var priceHtml = $(form).parent("td").parent("tr").children(".cart-item-price").text();
        var price = parseFloat(priceHtml);
        var summa = price * quantity;
        var summaHtml = $(form).parent("td").parent("tr").children(".cart-item-summa");
        summaHtml.text(summa);
    }

    function parseForm(form) {
        item.productId = form.find("input[type='hidden'][name='productId']").val();
        item.productImageId = form.find("input[type='hidden'][name='productImageId']").val();
        item.sizeId = form.find("input[type='hidden'][name='sizeId']").val();
        return item;
    }
    /*function for cart*/
    function addItemToCart(form) {

        item.productId = form.find("input[type='hidden'][name='productId']").val();
        item.productImageId = form.find("input[type='hidden'][name='productImageId']").val();
        item.sizeId = form.find("input[type='hidden'][name='sizeId']").val();
        item.quantity = form.find("input[type='text'][name='quantity']").val();
        if (item.quantity != "") {
            if ($.isNumeric(item.quantity)) {
                addItemToStore(item);
            }
            else {
                item.quantity = 0;
                addItemToStore(item);
            }
        }
    }
    function updateCart() {
        updateTotal();
        shop.showCartDetails();
    }
    function deleteItemCart(item) {
        var quantity = deleteItemFromStore(item);
        return quantity;
    }
    function decrementItemCartQuantity(item) {
        return decrementItemFromStore(item);
    }
    function incrimentItemCartQuantity(item) {
        return incrimentItemFromQuantity(item);
    }
    /*function for localStore*/
    function addItemToStore(item) {
        var key = generateKey(item);
        keys = getKeysFromStore();
        if ($.inArray(key, keys) != -1) {
            var oldItem = getItemFromStore(key);
            item.quantity = (parseInt(item.quantity) + parseInt(oldItem.quantity)).toString();
            localStorage.setItem(key, JSON.stringify(item));
        }
        else {
            localStorage.setItem(key, JSON.stringify(item));
            addKeyToStore(key);
        }

        currentItemIndex = currentItemIndex + 1;
    }
    function addKeyToStore(key) {
        keys = getKeysFromStore();
        keys.push(key);
        saveKeysToStore(keys);

    }
    function deleteItemFromStore(item) {
        var key = generateKey(item);
        localStorage.removeItem(key);
        deleteKeyFromStore(key);

    }
    function incrimentItemFromQuantity(item) {
        item.quantity = "1";
        addItemToStore(item);
        var key = generateKey(item);
        var item = getItemFromStore(key);
        return item.quantity;
    }
    function decrementItemFromStore(item) {
        var key = generateKey(item);
        var oldItem = getItemFromStore(key);
        if (parseInt(oldItem.quantity) > 1) {
            oldItem.quantity = (parseInt(oldItem.quantity) - 1).toString();
        }
        setItemToStore(oldItem);
        return oldItem.quantity;
    }
    function generateKey(item) {
        var key = item.productId +
                             item.productImageId +
                             item.sizeId;
        return key;
    }
    function deleteKeyFromStore(key) {
        keys = getKeysFromStore();
        keys.splice(keys.indexOf(key), 1);
        saveKeysToStore(keys);
    }
    function saveKeysToStore(keys) {
        localStorage.setItem('keys', JSON.stringify(keys));
    }
    function setItemToStore(item) {
        var key = generateKey(item);
        localStorage.setItem(key, JSON.stringify(item));
    }
    function getItemFromStore(key) {
        if (localStorage.getItem(key)) {
            var storeItem = localStorage.getItem(key);
            return $.parseJSON(localStorage.getItem(key));
        }
        else return null;
    }
    function getKeysFromStore() {
        if (localStorage.getItem('keys')) {
            var storeItem = localStorage.getItem('keys');
            return $.parseJSON(localStorage.getItem('keys'));
        }
        else return [];
    }
    /*function for connect to controllers*/
    function getProductsInsideCart() {
        keys = getKeysFromStore();
        var products = [];
        if (keys != null) {
            $.each(keys, function () {
                products.push($.parseJSON(localStorage.getItem(this)));
            });
        }
        return products;
    }
    function updateTotal() {
        var items = getProductsInsideCart();

        $.ajax({
            url: cartTotalUrl,
            type: "POST",
            data: JSON.stringify(items),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                //var text = $.parseJSON(data.responseText);
                $.each($('.cart-total'), function () {
                    $(this).html(data.total);
                });
            }

        });
    }

}
